package com.xiangzhi;

import nu.pattern.OpenCV;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class App {

    public static void main(String[] args) {
        OpenCV.loadShared();
        Mat src = loadImage("/Users/xz/Downloads/c.png");
        // 创建一个灰度图矩阵
        Mat grayImage = new Mat(src.rows(), src.cols(), CvType.CV_8SC1);

        // 将彩色图像转换为灰度图像
        Imgproc.cvtColor(src, grayImage, Imgproc.COLOR_BGR2GRAY);

        // 转换为灰度图
        Mat gray = new Mat();
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);

        // 二值化
        Mat binary = new Mat();
        Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV);

        //保存图像
        saveImage(binary, "/Users/xz/Downloads/d.png");
        System.out.println("Hello World!");

        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
        for (MatOfPoint contour : contours) {
            Rect rect = Imgproc.boundingRect(contour);
            Mat digit = new Mat(src, rect);
            String recognizedDigit = recognizeDigit(digit);
            System.out.println("Recognized Digit: " + recognizedDigit);
        }
    }

    public static Mat loadImage(String imagePath) {
        return Imgcodecs.imread(imagePath);
    }

    public static void saveImage(Mat imageMatrix, String targetPath) {
        Imgcodecs.imwrite(targetPath, imageMatrix);
    }

    public static String recognizeDigit(Mat digitImage) {
// 预处理图像
//        Imgproc.cvtColor(digitImage, digitImage, Imgproc.COLOR_BGR2GRAY);
//        Imgproc.threshold(digitImage, digitImage, 100, 255, Imgproc.THRESH_BINARY);
//
//        // 这里简化了特征提取和图像尺寸调整的步骤
//        // 假设digitImage已经是适合模型的尺寸和格式
//
//        // 使用KNN或其他分类器进行识别
//        // 这里的代码是伪代码，实际应用中需要根据训练的模型来调整
//        Mat response = new Mat();
//        knn.findNearest(digitImage.reshape(1, 1), 1, response);
//
//        return (int) response.get(0, 0)[0];
        return "0"; // Placeholder return
    }
}
